<?php


namespace app\controller;


use app\validate\User;
use think\exception\ValidateException;
use think\facade\Request;
use think\facade\Validate;
use think\validate\ValidateRule;
use think\annotation\Route;
use think\annotation\route\Validate as V;

class Verify
{
    //默认情况下，出现一个错误就会停止后面字段的验证，我们也可以设置批量验证
    //batch(true)
    //scene() 设置场景验证
   public function index(){
       try{
           validate(User::class)->batch(true)->scene('edit')->check(
               [
                   'name'=>'蜡笔小新',
                   'price'=>'90',
                   'email'=>'129985835@0qq.com'
               ]
           );
       }catch(ValidateException $e){
           dump($e->getError());
       }
   }

   //独立验证
   public function rule(){
//       $validate = Validate::rule([
//           'name'=>'require|max:20',
//           'price'=>'number|between:1,100',
//           'email'=>'email'
//       ]);

       //独立验证也支持闭包形式  这种方式不支持多规则。。。没用。。
//       $validate = Validate::rule([
//           'name'=>function($value){
//               return $value!=''?true:'姓名不得为空';
//           }
//       ]);


       $validate = Validate::rule([
           'name'=>ValidateRule::isRequire()->max(20),
           'price'=>ValidateRule::isNumber(null,'价格必须是数字')->between('1,100','价格在1~100之间'),
           'email'=>ValidateRule::isEmail(null,'邮箱格式不正确')
       ]);

       $validate->message([
          'name.require'=>['code'=>1001,'msg'=>'姓名不得为空'],
          'name.max'=>'姓名不得大于20位'
       ]);

       $result = $validate->batch(true)->check([
           'name'=>'蜡笔小新',
           'price'=>'90',
           'email'=>'1299858350@qq.com'
       ]);
       if(!$result){
           dump($validate->getError());
       }
   }

   //验证场景细节定义测试
    public function sct()
    {
        try{
            validate(User::class)->batch(true)->scene('save')->check(
                [
                    'name'=>'蜡笔小新',
                    'price'=>'90',
                    'email'=>'129985835@0qq.com'
                ]
            );
        }catch(ValidateException $e){
            dump($e->getError());
        }
    }

    //路由验证
    public function route($id){
       return 'id:'.$id;
    }

    //独立验证
    public function single(){
        dump(Validate::isNumber(1));
        dump(Validate::checkRule(100,'number|between:1,10'));
    }

    //注解路由验证


    /**
     * @param $id
     *
     * @return string
     * @route("rv/:id")
     * @V(User::class)
     */
    public function rv($id){
       return '11111111111';
    }

    public function token(){
//        echo session('__token__');
//        echo '<br>';
//        echo input('post.__token__');
        $check = Request::checkToken('__token');
        if($check==false){
            echo '令牌无效';
        }

    }
}